package com.factory.test.activity;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;

import androidx.databinding.DataBindingUtil;

import com.factory.test.base.BaseTestActivity;
import com.factory.test.R;
import com.factory.test.databinding.ActivityQrCodeBinding;
import com.yecontech.qrcode.QRCodeModule;
import com.yecontech.qrcode.QRScanException;
import com.yecontech.qrcode.ScanCallback;
import com.yecontech.qrcode.tty.TtyModule;

/**
 * 扫码测试
 */
public class QRcodeActivity extends BaseTestActivity {

    private Context context;
    private ActivityQrCodeBinding binding;
    private QRCodeModule qrCodeModule;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;

        binding = DataBindingUtil.setContentView(this, R.layout.activity_qr_code);
        binding.clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.textView.setText("");
            }
        });

        qrCodeModule = new TtyModule();
        Bundle bundle = new Bundle();
        bundle.putString(QRCodeModule.KEY_NODE, "/dev/ttyS1");
        bundle.putInt(QRCodeModule.KEY_BAUDRATE, 115200);
        bundle.putBoolean("beep", false);
        qrCodeModule.init(context, bundle);

    }

    @Override
    protected void onResume() {
        super.onResume();

        //todo 开始扫码
        qrCodeModule.start(new ScanCallback() {
            @Override
            public void onOpenSuccess() {

            }

            @Override
            public void onOpenError(QRScanException exception) {
                appendCard("ERROR ");
                appendCard(exception.getMessage());
            }

            @Override
            public void onScanResult(String code, String type) {
                appendCard("ttyS1: " + code);
            }
        });
    }

    private Handler handler = new Handler();
    private void appendCard(final String cardNo){
        handler.post(new Runnable() {
            @Override
            public void run() {
                if(binding.textView.length() > 10240){
                    binding.textView.setText("");
                }
                binding.textView.append(cardNo);
                binding.textView.append("\r\n");
                binding.scrollView.fullScroll(View.FOCUS_DOWN);
            }
        });
    }


    @Override
    protected void onPause() {
        super.onPause();
        qrCodeModule.stop();        //todo 停止, 释放设备
    }
}
